﻿namespace fleetIt
{
    using System.Windows;
    using Microsoft.Win32;
    using System.Reflection;

    /// <summary>
    /// Interaction logic for SettingsUI.xaml
    /// </summary>
    public partial class SettingsUI : Window
    {
        private const string STARTUP_REGISTRY = @"Software\Microsoft\Windows\CurrentVersion\Run";
        private const string APPNAME = "fleetIt";
        public SettingsUI()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.txtInterval.Text = Properties.Settings.Default.RefreshInterval.ToString();
        }

        private void SaveSettingsCommand_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
        {
            int currentValue = 0;
            e.CanExecute = this.txtInterval.Text.Length > 0 ? int.TryParse(this.txtInterval.Text, out currentValue) && currentValue >= 5 : false;
        }

        private void SaveSettingsCommand_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            if (this.chkInvokeAtStartUp.IsChecked.Value)
            {
                this.SetAutoStart(APPNAME, Assembly.GetExecutingAssembly().Location);
                //TODO: Need to implement registry stuff
            }
            else
            {
                this.UnSetAutoStart(APPNAME);
            }
            Properties.Settings.Default.LunchInWindowsStartup = this.chkInvokeAtStartUp.IsChecked.Value;
            Properties.Settings.Default.RefreshInterval = int.Parse(this.txtInterval.Text);
            Properties.Settings.Default.Save();
            this.Close();
        }
        private void SetAutoStart(string key, string executableLocation)
        {
            RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(STARTUP_REGISTRY);
            registryKey.SetValue(key, executableLocation);
        }

        private void UnSetAutoStart(string key)
        {
            RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(STARTUP_REGISTRY);
            registryKey.DeleteValue(key);
        }
    }
}
